package service

import (
	"MyBlogv2/blog-common/HttpCode"
	"MyBlogv2/blog-common/define"
	"MyBlogv2/blog-common/models"
	"MyBlogv2/blog-common/response"
	"github.com/gin-gonic/gin"
	"time"
)

func AddTreeHole(c *gin.Context) {
	var treeHole models.TreeHole
	userId, _ := c.Get("userId")
	if err := c.ShouldBind(&treeHole); err != nil {
		response.ResponseError(c, HttpCode.PARAM_ERROR)
		return
	}
	treeHole.UserId = userId.(int)
	err := models.Db.Model(new(models.TreeHole)).Create(&treeHole).Error
	if err != nil {
		response.ResponseError(c, HttpCode.FAILURE)
		return
	}
	response.ResponseOK(c, nil)
	return

}

func GetTreeHoleList(c *gin.Context) {
	var treeHoleVoList []models.TreeHoleVo
	models.Db.Model(new(models.TreeHole)).
		Table("t_tree_hole th").
		Select("th.*,u.nickname nickname,u.avatar avatar").
		Joins("left join sys_user u on th.user_id = u.id").
		Where("is_check = ?", define.IS_CHECK_YES).
		Order("created_at desc").
		Find(&treeHoleVoList)
	response.ResponseOK(c, treeHoleVoList)
	return

}

func GetTreeHoleList4Admin(c *gin.Context) {
	var treeHoleVoList []models.TreeHoleListVo
	models.Db.Model(new(models.TreeHoleListVo)).
		Table("t_tree_hole th").
		Select("th.*,u.username as username").
		Joins("left join sys_user u on th.user_id = u.id").
		Find(&treeHoleVoList)
	response.ResponseOK(c, treeHoleVoList)
	return
}

func SearchTreeHole(c *gin.Context) {
	var treeHoleVoList []models.TreeHoleListVo
	var searchTreeHoleDto models.SearchTreeHoleDto
	if err := c.ShouldBind(&searchTreeHoleDto); err != nil {
		response.ResponseError(c, HttpCode.PARAM_ERROR)
		return
	}
	db := models.Db.Model(new(models.TreeHoleListVo)).
		Table("t_tree_hole th").
		Select("th.*,u.username as username").
		Joins("left join sys_user u on th.user_id = u.id")
	if searchTreeHoleDto.Username != "" {
		db.Where("u.username like ?", "%"+searchTreeHoleDto.Username+"%")
	}
	if !time.Time(searchTreeHoleDto.StartTime).IsZero() {
		db.Where("th.created_at >= ?", searchTreeHoleDto.StartTime)
	}
	if !time.Time(searchTreeHoleDto.EndTime).IsZero() {
		db.Where("th.created_at <= ?", searchTreeHoleDto.EndTime)
	}
	if searchTreeHoleDto.IsCheck.Valid {
		db.Where("th.is_check = ?", searchTreeHoleDto.IsCheck.Int64)
	}
	db.Find(&treeHoleVoList)
	response.ResponseOK(c, treeHoleVoList)
	return
}

func UpdateTreeHoleIsCheck(c *gin.Context) {
	var treeHoleIsCheckDto models.TreeHoleIsCheckDto
	if err := c.ShouldBind(&treeHoleIsCheckDto); err != nil {
		response.ResponseError(c, HttpCode.PARAM_ERROR)
		return
	}
	models.Db.Model(new(models.TreeHole)).Where("id = ?", treeHoleIsCheckDto.Id).Update("is_check", treeHoleIsCheckDto.IsCheck)
	response.ResponseOK(c, nil)
	return
}

func DeleteTreeHole(c *gin.Context) {
	var ids []int
	if err := c.ShouldBindJSON(&ids); err != nil {
		response.ResponseError(c, HttpCode.PARAM_ERROR)
		return
	}
	models.Db.Model(new(models.TreeHole)).Where("id in (?)", ids).Delete(new(models.TreeHole))
	response.ResponseOK(c, nil)
	return
}
